package com.library.service.impl;

import com.library.entity.Book;
import com.library.entity.BorrowRecord;
import com.library.mapper.BookMapper;
import com.library.mapper.BorrowMapper;
import com.library.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class BorrowServiceImpl implements BorrowService {
    
    @Autowired
    private BorrowMapper borrowMapper;
    
    @Autowired
    private BookMapper bookMapper;
    
    @Override
    @Transactional
    public boolean borrowBook(BorrowRecord record) {
        // 检查图书是否可借
        Book book = bookMapper.findById(record.getBookId());
        if (book == null || book.getStatus() != 1 || book.getStock() <= 0) {
            return false;
        }
        
        // 检查用户是否有未归还的同一本书
        if (borrowMapper.findUnreturnedBook(record.getUserId(), record.getBookId()) > 0) {
            return false;
        }
        
        // 设置借阅信息
        record.setBorrowDate(new Date());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 3); // 设置三个月的借阅期限
        record.setReturnDate(calendar.getTime());
        record.setStatus(0);
        record.setOverdueFee(BigDecimal.ZERO);
        
        // 更新图书库存
        book.setStock(book.getStock() - 1);
        if (book.getStock() == 0) {
            book.setStatus(0); // 库存为0时设置为不可借
        }
        
        // 插入借阅记录
        boolean isRecordInserted = borrowMapper.insert(record) > 0;
        boolean isBookUpdated = bookMapper.update(book) > 0;
        
        return isRecordInserted && isBookUpdated;
    }
    
    @Override
    @Transactional
    public boolean returnBook(Integer id) {
        BorrowRecord record = borrowMapper.findById(id);
        if (record == null || record.getStatus() == 1) {
            return false;
        }
        
        // 计算逾期费用
        Date now = new Date();
        record.setActualReturnDate(now);
        if (now.after(record.getReturnDate())) {
            long diffInMillies = Math.abs(now.getTime() - record.getReturnDate().getTime());
            long overdueDays = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
            BigDecimal overdueFee = new BigDecimal(overdueDays * 0.5);
            record.setOverdueFee(overdueFee);
        }
        
        // 更新借阅记录状态
        record.setStatus(1);
        
        // 更新图书库存
        Book book = bookMapper.findById(record.getBookId());
        book.setStock(book.getStock() + 1);
        book.setStatus(1); // 有库存时设置为可借
        
        return borrowMapper.update(record) > 0 && bookMapper.update(book) > 0;
    }
    
    @Override
    public List<BorrowRecord> findByUserId(Integer userId) {
        List<BorrowRecord> records = borrowMapper.findByUserId(userId);
        // 计算在借图书的当前逾期费用
        Date now = new Date();
        for (BorrowRecord record : records) {
            if (record.getStatus() == 0 && now.after(record.getReturnDate())) {
                long diffInMillies = Math.abs(now.getTime() - record.getReturnDate().getTime());
                long overdueDays = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
                BigDecimal overdueFee = new BigDecimal(overdueDays * 0.5);
                record.setOverdueFee(overdueFee);
            }
        }
        return records;
    }
    
    @Override
    public List<BorrowRecord> findAll() {
        return borrowMapper.findAll();
    }
} 